<template>
  <view class="main">
	<tabar :current="1"></tabar>	
	<view class="class_h" style="background: linear-gradient(180deg, #91c8ec 0%, #f9f9f9 28.08%)">
	        <view class="top">血糖血压小程序</view>
	   
		    <view class="flex blood_top">
				<view class="flex">
					<image src="/static/resource/blood_sugar.png" class="blood_sugar" v-if="blood_type ==1 " @click="select_blood(1)"></image>
					<image src="/static/resource/blood_sugar1.png" class="blood_pressure" v-if="blood_type ==2 " @click="select_blood(1)"></image>
				</view>
				<view class="flex ml-30">
					<image src="/static/resource/blood_pressure.png" class="blood_pressure" v-if="blood_type ==1 " @click="select_blood(2)"></image>
					<image src="/static/resource/blood_pressure1.png" class="blood_sugar" v-if="blood_type ==2 " @click="select_blood(2)"></image>
				</view>
		    </view>
		   
		    <!-- 血糖 -->
		    <view class="flex total"  v-if="blood_type ==1 "> 						  
				<view class="effect_title">
					<view class="flex justify-start align-center text-center">
						<view class="flex">
							<image src="../../static/resource/sugar_icon.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
						</view>
						<text class="effect_t ml-15">血糖（mmol/L）</text>
					</view>					
					<view class="flex align-center text-center" @click="more_list(1)">
						<text style="color: #867f7f;">历史记录</text>
						<view class="flex ml-10">
							<u-icon name="arrow-right"  color="#867f7f" size="14"></u-icon>
						</view>
					</view>					
				</view>
				
				<view class="bubble-container">
					<text class="bubble">{{blood_sugar}}</text>
					<text class="unit"> mmol/l</text>	
					<text class="unit low" style="margin-top: 20px;background-color: red" v-if="super_range=='偏低'">偏低</text>
					<text class="unit low" style="margin-top: 20px;background-color: #1EC157" v-if="super_range=='正常'">正常</text>	
					<text class="unit low" style="margin-top: 20px;background-color: #F56202" v-if="super_range=='偏高'">偏高</text>	
				</view>
				
				  
				<view class="ruler-box">
					<!-- 两边渐变遮罩 -->
					<view class="fade-left"></view>
					<view class="fade-right"></view>
					<!-- 横向可滑动刻度 -->
					<slide-choose :width="100" :bigItemWidth="2" :littleItemWidth="2" @change="chooseChange" height="120"
								:cellWidth="6" :cells="10" :cellNum="0.1" :startNum="1" :endNum="30" color="#867f7f" :bigItemHeight="20"
								:littleItemHeight="10" selColor="#3484E6" bgColor="#efefef" align="flex-end" numPos="bottom" v-model="blood_sugar"></slide-choose>				
				 </view>				
				<view class="containert">
					<!-- 左边日期 -->
					<view class="box-container">
					    <scroll-view  
						  scroll-y
						  class="box"
						  :scroll-top="scrollTop"
						  scroll-with-animation
						  >
						  <view
							v-for="(day, index) in dateList"
							:key="index"
							class="item"
							:class="{ active: selectedDate === index }"
							@click="selectedDate = index"
						  >
							{{ day }}
						  </view>
					     </scroll-view>
					  </view>
			
					<!-- 右边时间段 -->
					<view class="box-container">
					    <scroll-view  
						  scroll-y
						  class="box"
						  :scroll-top="scrollTops"
						  scroll-with-animation
						  >
						  <view
							v-for="(period, index) in timeList"
							:key="index"
							class="item"
							:class="{ active: selectedTime === index }"
							@click="selectedTime = index"
						  >
							{{ period }}
						 </view>
						 </scroll-view>
					</view>
				</view>				  
		    </view>
		   
		   
		   <!-- 血压 -->
		   <view class="flex total"  v-if="blood_type ==2 ">							
							
				<view class="effect_title">
					<view class="flex justify-start align-center text-center">
						<view class="flex">
							<image src="../../static/resource/pressure_icon.png" mode="aspectFill" style="width: 18px;height: 18px;"></image>
						</view>
						<text class="effect_t ml-15">血压（mmhg）</text>
					</view>
					<view class="flex align-center text-center" @click="more_list(2)">
						<text style="color: #867f7f;">历史记录</text>
						<view class="flex ml-10">
							<u-icon name="arrow-right"  color="#867f7f" size="14"></u-icon>
						</view>
					</view>		
				</view>
				
				
				<view class="flex justify-between mt-30">					
					<view class="left" >
						<view class="flex flex-direction pt-30 pl-20">
							<view class="flex mb-15">
								<text class="bubble" style="font-size: 16px;color: #333333;">收缩压</text>
							</view>
							<view class="flex">
								<text class="bubble">{{sbpData}}</text>
								<text class="units  pt-30 pl-10">mmol/l</text>	
							</view>
							<text class="unit low" style="margin-top: 5rpx;background-color: red" v-if="sbp_range=='偏低'">偏低</text>	
							<text class="unit low" style="margin-top: 5rpx;background-color: #1EC157" v-if="sbp_range=='正常'">正常</text>	
							<text class="unit low" style="margin-top: 5rpx;background-color: #F56202" v-if="sbp_range=='偏高'">偏高</text>	
						</view>					  
						<view class="ruler-box">
							<!-- 两边渐变遮罩 -->
							<view class="fade-left"></view>
							<view class="fade-right"></view>
							<!-- 横向可滑动刻度 -->
							<slide-choose :width="50" :bigItemWidth="2" :littleItemWidth="2" @change="chooseChange" height="120"
										:cellWidth="6" :cells="10" :cellNum="1" :startNum="80" :endNum="180" color="#867f7f" :bigItemHeight="20"
										:littleItemHeight="10" selColor="#3484E6" bgColor="#efefef" align="flex-end" numPos="bottom" v-model="sbpData"></slide-choose>				
						 </view>	
					</view>					
					<view class="right">
							<view class="flex flex-direction pt-30 pl-30">
								<view class="flex mb-15">
									<text class="bubble" style="font-size: 16px;color: #333333;">舒张压</text>
								</view>
								<view class="flex">
									<text class="bubble">{{dbpData}}</text>
									<text class="units  pt-30 pl-10">mmhg</text>	
								</view>
								<text class="unit low" style="margin-top: 5rpx;background-color: red" v-if="dbp_range=='偏低'">偏低</text>
								<text class="unit low" style="margin-top: 5rpx;background-color: #1EC157" v-if="dbp_range=='正常'">正常</text>	
								<text class="unit low" style="margin-top: 5rpx;background-color: #F56202" v-if="dbp_range=='偏高'">偏高</text>
							</view>					  
							<view class="ruler-box">
								<!-- 两边渐变遮罩 -->
								<view class="fade-left"></view>
								<view class="fade-right"></view>
								<!-- 横向可滑动刻度 -->
								<slide-choose :width="50" :bigItemWidth="2" :littleItemWidth="2" @change="chooseChange" height="120"
											:cellWidth="6" :cells="10" :cellNum="1" :startNum="40" :endNum="120" color="#867f7f" :bigItemHeight="20"
											:littleItemHeight="10" selColor="#3484E6" bgColor="#efefef" align="flex-end" numPos="bottom" v-model="dbpData"></slide-choose>				
							 </view>	
					</view>					
				</view>
				
				<view class="containert mt-40">
					<!-- 左边日期 -->
					<view class="box-container">
					    <scroll-view  
						  scroll-y
						  class="box"
						  :scroll-top="scrollTop"
						  scroll-with-animation
						  >
						  <view
							v-for="(day, index) in dateList"
							:key="index"
							class="item"
							:class="{ active: selectedDate === index }"
							@click="selectedDate = index"
						  >
							{{ day }}
						  </view>
						   </scroll-view>
					</view>
							
					<!-- 右边时间段 -->
					<view class="box-container">
					    <scroll-view  
						  scroll-y
						  class="box"
						  :scroll-top="scrollTops"
						  scroll-with-animation
						  >
						  <view
							v-for="(periods, index) in timeLists"
							:key="index"
							class="item"
							:class="{ active: selectedTimes === index }"
							@click="selectedTimes = index"
						  >
							{{ periods }}
						  </view>
						 </scroll-view>
					</view>
				</view>					
		   </view>			  
        </view>	
		
		<view class="flex submit_icon" @click="userInfo.token?submitGage():$routers.routeToLogin()">
			 <image src="/static/resource/submit.png"  style="width: 686rpx;height: 88rpx;"></image>
		</view>
		
		
		
		
		
	<!-- 弹框部分 -->
	<u-popup
	  :show="userInfo.token && userInfo.is_information==0"
		  mode="center"
		  round="20"
		  :closeOnClickOverlay="false"
		  @close="showPopup = false"
		>
		  <view class="popup-box">
			<image
			  class="popup-icon"
			  src="/static/images/info.png"
			  mode="aspectFit"
			></image>
			<text class="popup-title">请完善个人信息</text>
			<text class="popup-desc mt-30">为了提供更好的服务，请先完善您的个人资料。</text>
			
			<view class="btn-group">
			  <u-button
				type="primary"
				color="#6EBA44"
				shape="circle"
				@click="goCompleteInfo"
			  >去完善</u-button>
			</view>
		  </view>
	</u-popup>
		
  </view>
</template>

<script>
	
	import slideChoose from '@/components/dlm-slide-choose/dlm-slide-choose.vue';
	export default {
		components: {	
			slideChoose,
		},		
		data() {
			const app = getApp()
			return {
				...getApp().globalData.config,
				blood_sugar: 6.1,	
			    blood_type:1,
				dateList: [], // 动态生成最近3天
			    timeList: ['凌晨', '空腹', '早餐后', '午餐前', '午餐后'],
			    selectedDate: null, // 当前选中的日期索引
			    selectedTime: 0  ,// 当前选中的时间索引
				sbpData:120,//收缩压 范围	说明90 ~ 140 mmHg,
				dbpData:80,//舒张压（DBP）正常值 60 ~ 90 mmHg
				timeLists: ['清晨', '白天', '晚上',],
				selectedTimes:0,
				userInfo:{},
				super_range:'正常',
				sbp_range:'正常',
				dbp_range:'正常',
				scrollTop: 0 ,// ✅ 控制 scroll-view 滚动位置
				scrollTops:0,
			}
		},
		
		mounted() {
		    this.generateDateList()
		  },
		  
		onShow() {
			let user_info=uni.getStorageSync('userInfo');
			let that=this;
			if(user_info){
				let obj_data={
					token:user_info.token,
				    login_type:'app'
				};
				this.$http.getUser(obj_data).then(res=>{				
					if(res.resCode=='9999'){
						uni.setStorageSync('userInfo',res.data);	
					    that.userInfo=res.data	
						that.timeList=res.data.tags_list			
					}				
				})				
			}else{
				 that.userInfo=''
			}
		}, 
		methods: {
			...getApp().globalData.funcion,
			
			
			//完善信息
			goCompleteInfo(){
				this.$routers.router('/pages/pagesuser/member_set/member_base','navigateTo') 
			},
			
			//提交测量信息
			submitGage(){				
				let obj={
					token:uni.getStorageSync('userInfo').token,
					blood_type:this.blood_type,//1：血糖，2：血压				
					dateTime:this.dateList[this.selectedDate], //时间					
					sugar_type:this.selectedTime,
					sugar_value:this.timeList[this.selectedTime],					
				}
				if(this.blood_type == 1 ){
					obj.blood_sugar=this.blood_sugar//血糖		
					obj.super_range=this.super_range
				}else{					
					obj.blood_sbp=this.sbpData//血糖
					obj.blood_dbp=this.dbpData//血糖
					obj.sugar_type=this.selectedTimes//
					obj.sugar_value=this.timeLists[this.selectedTimes]//	
					obj.sbp_range=this.sbp_range
					obj.dbp_range=this.dbp_range
				}				
				this.$http.subBlood(obj).then(res=>{
					if (res.resCode == '9999') {
					    uni.showToast({title:res.resMessage,icon:"success"})
					}else{
						uni.showToast({title:res.resMessage,icon:"error"})
					}
				})
				
			},
			
			
			// 生成今天和前两天的日期
			generateDateList() {
			      const dates = []
			      const today = new Date()
			      for (let i = 7; i >= 0; i--) {
			        const d = new Date()
			        d.setDate(today.getDate() - i)
			        const dateStr =
			          i === 0
			            ? '今天'
			            : `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
			                d.getDate()
			              ).padStart(2, '0')}`
			        dates.push(dateStr)
			      }
			      this.dateList = dates
			      this.selectedDate = dates.length - 1 // ✅ 默认选中“今天”
				  
				// ✅ 页面渲染完后自动滚动到底部
				this.$nextTick(() => {
				  const itemHeight = 80 // 每个 item 高度 (rpx 换算约等于 px)
				  this.scrollTop = this.dateList.length * itemHeight
				})
						
			},
			select_blood(type){
				this.blood_type=type
			},
			//点击领取
			receive(type){
				if(type==1) this.is_receive_points=1
				if(type==2) this.is_receive_coupon=2
			},
			chooseChange(e) {
				this.check_sugar()
			},
			handleEdit() {
				const {
					value
				} = this;
				if (value >= 0) {
					this.value++;
				}
			},
			
			//更多记录
			more_list(type){
				if(type ==1) this.$routers.router('/pages/class/sugar_list/index','navigateTo') 
				if(type ==2) this.$routers.router('/pages/class/pressure_list/index','navigateTo') 
			},
			
			//血糖过低，正常，过高判断
			check_sugar(){
				if(this.blood_type==1){
					let blood_sugar=this.blood_sugar//血糖	
					let sugar_text=this.checkBloodSugar(this.selectedTime,blood_sugar)
					this.super_range=sugar_text.status
					console.log('sugar_text',sugar_text)
						// '0'=>'凌晨',        
						// '1'=>'空腹',
						// '2'=>'早餐后',//用户-待发货，团长-未到货，//仓储-待采购(待打包)
						// '3'=>'午餐前',//用户-待发货状态不变，，团长-未到货状态不变，仓储-已发货
						// '4'=>'午餐后',     
						// '5'=>'晚餐前',  
						// '6'=>'晚餐后', 
						// '7'=>'睡前',					
				}else{
					let sbp_content= this.checkSystolicByTime(this.timeLists[this.selectedTimes],this.sbpData);
					let dbp_content=this.checkDiastolicByTime(this.timeLists[this.selectedTimes],this.dbpData);
					this.sbp_range=sbp_content.status
					this.dbp_range=dbp_content.status
					console.log('content',sbp_content,)
				}
			},
			checkBloodSugar(timeCode, value) {
				  // 各时间段正常范围
				  const ranges = {
					0: [3.9, 6.1], // 凌晨
					1: [3.9, 6.1], // 空腹
					2: [4.4, 7.8], // 早餐后
					3: [3.9, 6.1], // 午餐前
					4: [4.4, 7.8], // 午餐后
					5: [3.9, 6.1], // 晚餐前
					6: [4.4, 7.8], // 晚餐后
					7: [4.4, 6.9], // 睡前
				  };
				
				  const range = ranges[timeCode] || [3.9, 6.1];
				  const [low, high] = range;
				
				  let status = '正常';
				  if (value < low) status = '偏低';
				  else if (value > high) status = '偏高';
				
				  return {
					'status': status,
					'sugar_range': `${low}～${high}`,
				  };
				},
				
				checkSystolicByTime(timePeriod, sbp) {
				  // 定义不同时间段的正常范围
				  const ranges = {
					'清晨': [90, 145],
					'白天': [90, 139],
					'晚上': [85, 135]
				  };
				
				  // 获取范围，默认白天
				  const [low, high] = ranges[timePeriod] || ranges['白天'];
				
				  let status = '正常';
				  if (sbp < low) status = '偏低';
				  else if (sbp > high) status = '偏高';
				
				  return {
					时间段: timePeriod,
					收缩压: sbp,
					正常范围: `${low}～${high}`,
					'status': status
				  };
			},
			checkDiastolicByTime(timePeriod, dbp) {
				  // 定义不同时间段的正常范围
				  const ranges = {
					'清晨': [60, 95],
					'白天': [60, 89],
					'晚上': [55, 85]
				  };
				
				  // 获取范围，默认白天
				  const [low, high] = ranges[timePeriod] || ranges['白天'];
				
				  let status = '正常';
				  if (dbp < low) status = '偏低';
				  else if (dbp > high) status = '偏高';
				
				  return {
					时间段: timePeriod,
					舒张压: dbp,
					正常范围: `${low}～${high}`,
					'status': status
				  };
			}
			
			
		}
	  
	};
</script>

<style scoped>
  @import "./index.css";
</style>
